package com.example.teaching_server.service;

import com.example.teaching_server.dto.MenuDTO;
import com.example.teaching_server.entity.*;
import com.example.teaching_server.repository.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 教学资源服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class TeachingResourceService {

    private final TeachingCategoryRepository categoryRepository;
    private final TeachingSubcategoryRepository subcategoryRepository;
    private final TeachingResourceTypeRepository resourceTypeRepository;
    private final TeachingResourceRepository resourceRepository;
    private final GradeRepository gradeRepository;

    /**
     * 获取左侧菜单（所有年级+分类+子类）
     */
    public List<MenuDTO> getLeftMenu() {
        log.debug("获取教学资源左侧菜单");

        return gradeRepository.findAllGrades().stream()
                .map(this::convertGradeToMenuDTO)
                .collect(Collectors.toList());
    }

    /**
     * 获取所有资源类型
     */
    public List<TeachingResourceType> getAllResourceTypes() {
        log.debug("获取所有资源类型");
        return resourceTypeRepository.findAllByOrderBySortOrderAsc();
    }

    /**
     * 根据条件获取资源
     */
    public List<TeachingResource> getResourcesByCriteria(Long subcategoryId, Integer typeId, String keyword) {
        log.debug("根据条件查询资源: subcategoryId={}, typeId={}, keyword={}", subcategoryId, typeId, keyword);

        String searchKeyword = normalizeKeyword(keyword);

        if (searchKeyword != null) {
            return searchResourcesWithKeyword(subcategoryId, typeId, searchKeyword);
        } else {
            return searchResourcesWithoutKeyword(subcategoryId, typeId);
        }
    }

    /**
     * 转换年级为菜单DTO
     */
    private MenuDTO convertGradeToMenuDTO(Grade grade) {
        MenuDTO menuDTO = new MenuDTO();
        menuDTO.setGradeId(Math.toIntExact(grade.getGradeId()));
        menuDTO.setGradeName(grade.getGradeName());

        List<MenuDTO.CategoryDTO> categories = categoryRepository
                .findByGradeIdOrderBySortOrderAsc(grade.getGradeId())
                .stream()
                .map(this::convertCategoryToDTO)
                .collect(Collectors.toList());

        menuDTO.setCategories(categories);
        return menuDTO;
    }

    /**
     * 转换分类为DTO
     */
    private MenuDTO.CategoryDTO convertCategoryToDTO(TeachingCategory category) {
        MenuDTO.CategoryDTO categoryDTO = new MenuDTO.CategoryDTO();
        categoryDTO.setId(category.getId());
        categoryDTO.setName(category.getName());
        categoryDTO.setIcon(category.getIcon());

        List<MenuDTO.SubcategoryDTO> subcategories = subcategoryRepository
                .findByCategoryIdOrderBySortOrderAsc(category.getId())
                .stream()
                .map(this::convertSubcategoryToDTO)
                .collect(Collectors.toList());

        categoryDTO.setSubcategories(subcategories);
        return categoryDTO;
    }

    /**
     * 转换子分类为DTO
     */
    private MenuDTO.SubcategoryDTO convertSubcategoryToDTO(TeachingSubcategory subcategory) {
        MenuDTO.SubcategoryDTO subcategoryDTO = new MenuDTO.SubcategoryDTO();
        subcategoryDTO.setId(subcategory.getId());
        subcategoryDTO.setName(subcategory.getName());
        return subcategoryDTO;
    }

    /**
     * 规范化关键字
     */
    private String normalizeKeyword(String keyword) {
        if (keyword != null && !keyword.trim().isEmpty()) {
            return keyword.trim();
        }
        return null;
    }

    /**
     * 带关键字搜索资源
     */
    private List<TeachingResource> searchResourcesWithKeyword(Long subcategoryId, Integer typeId, String keyword) {
        if (subcategoryId != null && typeId != null && typeId != 0) {
            return resourceRepository.findBySubcategoryIdAndTypeIdAndKeyword(subcategoryId, typeId, keyword);
        } else if (subcategoryId != null) {
            return resourceRepository.findBySubcategoryIdAndKeyword(subcategoryId, keyword);
        } else {
            return resourceRepository.findByKeyword(keyword);
        }
    }

    /**
     * 不带关键字搜索资源
     */
    private List<TeachingResource> searchResourcesWithoutKeyword(Long subcategoryId, Integer typeId) {
        if (typeId == null || typeId == 0) {
            return resourceRepository.findBySubcategoryId(subcategoryId);
        } else {
            return resourceRepository.findBySubcategoryIdAndTypeId(subcategoryId, typeId);
        }
    }
}
